<?php
  $context = stream_context_create(array(
    'http' => array(
      'header' => "Authorization: Basic ".base64_encode('bce:trade2012')
    )
  ));
  $isRegistered = $_REQUEST['isRegistered'] == 'true';


  // try to search by owner name 1st
  $u = explode('/',$_SERVER['REQUEST_URI']);
  array_pop($u);
  $u = 'http://'.$_SERVER['SERVER_NAME'].implode('/',$u).'/getParcelsByBbox.php';
  $json = json_decode(file_get_contents($u.'?swLon=-180&swLat=-90&neLon=180&neLat=90&regulatedOnly=false&dir=A&sort='.urlencode($isRegistered ? 'Owner Name' : 'Phys Addr1').'&query='.urlencode($_REQUEST['query'])."&isRegistered=".$_REQUEST['isRegistered'],false,$context),true);
  if (count($json['data']) > 0) {
    echo json_encode(array('data' => array(
       'id'      => 0
      ,'parcels' => $json['data']
    )));
  }
  else {
    $xml = simplexml_load_string(file_get_contents("http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address=".urlencode($_REQUEST['query'])));
    $swLat  = $xml->xpath('result/geometry/viewport/southwest/lat');
    $swLon  = $xml->xpath('result/geometry/viewport/southwest/lng');
    $neLat  = $xml->xpath('result/geometry/viewport/northeast/lat');
    $neLon  = $xml->xpath('result/geometry/viewport/northeast/lng');
    echo json_encode(array('data' => array(
       'id'    => 0
      ,'swLon' => (string)$swLon[0]
      ,'swLat' => (string)$swLat[0]
      ,'neLon' => (string)$neLon[0]
      ,'neLat' => (string)$neLat[0]
    )));
  }
?>
